/**
 * 
 */
package com.honghao.student.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
/**
 * @author honghao.li
 * 
 */
public abstract class AbstroctController {

    private static final Logger LOGGER = LoggerFactory
            .getLogger(AbstroctController.class);
    
    /**
     * @param e
     *            Exception
     * @return response json string
     */
    @ExceptionHandler(Exception.class)
    //@ResponseBody
    public String handleException(Exception e) {
        if (e instanceof HttpMessageNotReadableException) {
            LOGGER.warn(e.getMessage(), e);
            //return String.format("PARAMETER ERROR", getOperationName());
        }
        LOGGER.error(e.getMessage(), e);
        //return String.format("SYSTEM_ERROR", getOperationName());
        return "error.jsp";
    }

    /**
     * @param result
     *            true/false
     * @param responseBean
     *            responseBeans
     * @return true if has errors;false if has not errors.
     */
    protected boolean hasNotErrors(BindingResult result) {
        if (result.hasFieldErrors()) {

            StringBuilder errorMessage = new StringBuilder();
            errorMessage.append("Parameter error!");
            for (FieldError fieldError : result.getFieldErrors()) {
                errorMessage.append(",{'");
                errorMessage.append(fieldError.getField());
                errorMessage.append("' ");
                errorMessage.append(fieldError.getDefaultMessage());
                errorMessage.append("}");
            }
            LOGGER.warn(errorMessage.toString());
            return false;
        }
        return true;
    }

    /**
     * @return operation name
     */
    //protected abstract String getOperationName();

}
